import Utils.utils as utils
import os,sys
from django.http import HttpResponse
from django.shortcuts import render
from Utils.config import VIR_DIR,getPublicPath
import re
from Utils.language import LNG
import Explorer.utils as Eu
import Explorer.utils as U
class Explorer(utils.Controller):
    def pathlist(self,path):
        test = path
        req_path = os.path.dirname(path)
        req_name = os.path.basename(path)

        ret = re.match("\{(.+)\}(\:[0-9]*)?(.+)", path.replace('\\','/'))
        DIR_NAME = ""
        pathType = ""
        GID = ""
        if ret is not None:
            v_dir = ret.group(1)
            pathType = "{" + v_dir + "}"
            return self.show_json({
                "fileList":[],
                "folderList":[{
                "atime": 1553509521
                ,"ctime": 1553509521
                ,"isParent": False
                ,"isReadable": 1
                ,"isWriteable": 1
                ,"mode": "drwx rwx rwx(0777)"
                ,"mtime": 1553509521
                ,"name": "示例指向公共目录"
                ,"path": getPublicPath()
                ,"type": "folder"
            }]
                ,"thisPath": "收藏夹"
            })
            base = VIR_DIR[v_dir]
            path = base + ret.group(3)
            GID = ret.group(2)
            if GID:
                DIR_NAME = "public"
        path = os.path.abspath(os.path.dirname(path) + '/' + os.path.basename(path))
        if not os.path.exists(path):
            path = "/"
        files = os.listdir(path)

        folderList = []
        fileList = []
        for i in files:
            isD, fdic = self.filedict(path + '/' + i)
            if isD:
                folderList.append(fdic)
            else:
                fileList.append(fdic)

        data = {
            "folderList": folderList
            , "fileList": fileList
            , "info": {
                "pathType": pathType,
                "role": "",
                "id": "" if not GID else GID.split(':')[-1],
                "name": DIR_NAME
            },
            "pathReadWrite": "writeable",
            "thisPath": req_path.replace('\\','/'),
            "userSpace": {
                "sizeMax": "0",
                "sizeUse": 1024
            }
            , "test": test
        }
        return self.show_json(data)

    def filedict(self,file):
        mode = {
            '0': "---"
            , '1': "--x"
            , '2': "-w-"
            , '3': "-wx"
            , '4': "r--"
            , '5': "r-x"
            , '6': "rw-"
            , '7': "rwx"
        }

        pra = os.stat(file)
        prg = oct(os.stat(file).st_mode)[-3:]
        _file = {
            "name": os.path.basename(file),
            "path": file.replace('\\','/'),
            "mode": mode[prg[0]] + mode[prg[1]] + mode[prg[2]] + " (" + prg + ")",
            "atime": (int)(pra.st_atime),
            "ctime": (int)(pra.st_ctime),
            "mtime": (int)(pra.st_mtime),
            "isReadable": int(prg[0]) in [4, 5, 6, 7],
            "isWriteable": int(prg[0]) in [2, 3, 6, 7],

        }
        if os.path.isdir(file):
            _file.update(
                {
                    "type": "folder"
                    , "isParent": True
                }
            )
            return True, _file
        else:
            _file.update(
                {
                    "type": "file"
                    , "size": os.path.getsize(file)
                    , "isParent": False
                    , "ext": os.path.splitext(file)[-1][1:]
                }
            )
            return False, _file

    def treelist(self,request):
        indata = request.GET
        type = None
        if indata.__contains__('type'):
            type = indata['type']
        app = 'explorer'
        if indata.__contains__('app'):
            app = indata['app']

        if not type == 'init':
            indata = request.POST
            path = indata['path']

            return self.show_json(Eu.VTDirList(path))
        baseDir= self.get_database_dir()
        assert baseDir is not None,baseDir
        fav = {
                "name": "收藏夹",
                "ext": "tree-fav",
                "menuType": "menu-tree-fav-root",
                "children": Eu.VTDirList_Fav(),
                "path": "{userFav}",
                "type": "folder",
                "open": True,
                "isParent": False
            }
        mydir = baseDir + '/User'
        pubDir = baseDir + '/Public'
        my = {
            "name": "我的文档",
            "menuType": "menu-tree-root",
            "ext": "tree-self",
            "children": Eu.VTDirList(mydir),
            "path": mydir,
            "type": "folder",
            "open": True,
            "isParent": True
        }

        pub = {
            "name": "公共目录",
            "menuType": "menu-tree-group-root menu-tree-group-public",
            "ext": "group-public",
            "children":Eu.VTDirList(pubDir),
            "path": pubDir,
            "type": "folder",
            "open": True,
            "isParent": True
        }

        tree = [ fav,my,pub ]
        return self.show_json(tree)
    #两种情况 单个文件 其他
    def pathInfo(self,request):
        indata = request.POST["dataArr"]
        import json
        infoList = json.loads(indata)

        if not infoList:
            return self.show_json({"error":LNG('error'), "state:":False})

        for val in infoList:
            val['path'] = U._DIR(val['path'])

        data = U.path_info_muti(infoList, LNG('time_type_info'))
        if not data:
            return self.show_json({"error":LNG('not_exists'), "state":False})
        # 属性查看，单个文件则生成临时下载地址。没有权限则不显示
        if len(infoList) == 1:
            #单个文件或目录

            data['fileMd5'] = "...";
        #获取图片尺寸

        return self.show_json(data)
    #
    def search(self,request):
        indata = request.POST
        if indata['search'] is None:
            return self.show_json(LNG('please_inpute_search_words'),False)
        search = indata['search']
        isContent = int(indata['is_content'])
        isCase = int(indata['is_case'])
        ext = indata['ext']
        path = os.path.abspath(indata['path'])
        fileList = []
        folderList = []
        if not isCase:
            search = search.lower()
        for root ,dirs,files in os.walk(path):
            for dir in dirs:
                if not isCase:
                    dir = dir.lower()
                if search in dir:
                    tash,ret = U.filedict(root+'/'+dir)
                    folderList.append(ret)
            for file in files:
                if not isCase:
                    file = file.lower()
                if search in file and file.endswith('' if not ext else '.'+ext):
                    tash, ret = U.filedict(root + '/' + file)
                    fileList.append(ret)

        return self.show_json({"fileList":fileList,"folderList":folderList})

    def mkdir(self,request):
        indata = request.GET
        path = indata['path']
        try:
            os.mkdir(path)
        except Exception as e:
            info = str(e)
            return self.show_json(LNG("fail"), info=info,state=False)
        return self.show_json(LNG("success"),info=path)

    def rname(self,request):
        indata = request.POST
        try:
            os.rename(indata['path'],indata['rnameTo'])
        except Exception as e:
            info = str(e)
            return self.show_json(LNG('fail'), info=info,state=False)

        return self.show_json(LNG('success'),info=indata['rnameTo'])

    def mkfile(self,request):
        indata = request.GET
        path = indata['path']
        if os.path.exists(path):
            return self.show_json(LNG("exist!"), info=LNG('it has exist'), state=False)
        try:
            f = open(path,'w+')
            f.close()
        except Exception as e:
            info = str(e)
            return self.show_json(LNG("fail"), info=info, state=False)
        return self.show_json(LNG("success"), info=path)

    def pathDelete(self,request):
        indata = request.POST
        import json
        list = json.loads( indata['dataArr'])

        try:
            for obj in list:
                if obj['type']=='folder':
                    for root,dirs,files in os.walk(obj['path'],topdown=False):
                        for d in dirs:
                            os.rmdir(root+'/'+d)
                        for f in files:
                            os.remove(root+'/'+f)
                    os.rmdir(obj['path'])
                else:
                    os.remove(obj['path'])
        except Exception as e:
            info = str(e)
            return self.show_json(LNG('fail'),info=info,state=False)
        return self.show_json(LNG("success"))

    #建议刷新的时候 清理一次copy
    def pathCopy(self,request):
        from Utils.config import TEMP_DIR
        from json import dumps
        if not os.path.exists(TEMP_DIR):
            os.mkdir(TEMP_DIR)
        try:
            copyTemp = open(TEMP_DIR+"/"+'copyFile','w');
            indata = request.POST
            storage = {"operateType":"copy","data":indata}
            copyTemp.write(dumps(storage))
            copyTemp.close()
        except Exception as e:
            info = str(e)
            return self.show_json(LNG("fail"), info=info, state=False)
        return self.show_json(LNG("copy success"))

    def pathCut(self,request):
        from Utils.config import TEMP_DIR
        from json import dumps
        if not os.path.exists(TEMP_DIR):
            os.mkdir(TEMP_DIR)
        try:
            copyTemp = open(TEMP_DIR+"/"+'copyFile','w');
            indata = request.POST
            storage = {"operateType": "cut", "data": indata}
            copyTemp.write(dumps(storage))
            copyTemp.close()
        except Exception as e:
            info = str(e)
            return self.show_json(info, info=LNG("fail"), state=False)
        return self.show_json(LNG("cut pre success"))
    def pathCutDrag(self,request):
        indata = request.POST
        path = indata['path']
        from json import loads
        from shutil import move

        try:
            copyData = loads(indata['dataArr'])
            for obj in copyData:
              move(obj['path'], path)
        except Exception as e:
            info = str(e)
            return self.show_json(info, info=LNG("fail"), state=False)

        return self.show_json(LNG("move success"), info=copyData)
    def pathPaste(self,request):
        indata = request.GET
        path = indata['path']
        from Utils.config import TEMP_DIR
        from json import loads
        from shutil import copytree,copy2,move
        if not os.path.exists(TEMP_DIR+'/'+'copyFile'):
            return self.show_json(LNG("copyboard not exist or expire"),state=False)
        copyData = "init"
        try:
            copyTemp = open(TEMP_DIR+"/"+'copyFile','r');
            storage =  loads(copyTemp.read())
            copyTemp.close()
            os.remove(TEMP_DIR+"/"+'copyFile')

            copyData = loads(storage['data']['dataArr'])

            if storage['operateType']=='cut':
                for obj in copyData:
                     move(obj['path'],path)
            else:
                for obj in copyData:
                    if obj['type'] == 'folder':
                        copytree(obj['path'], path)
                    else:
                        copy2(obj['path'], path)
        except Exception as e:
            info = str(e)
            return self.show_json(info, info=LNG("fail"), state=False)
        return self.show_json(LNG("paste success"),info=copyData)

    def image(self,request,path,time):
       # os.path.splitext(file)[-1][1:]
       try:
            img = open(path,'rb')
            return HttpResponse(img.read(), content_type="image/*")
       except Exception as e:
            return HttpResponse(str(e))
